//
//  JiandanTableViewControlle.swift
//  Jiandan
//
//  Created by guoqw on 15/9/6.
//  Copyright (c) 2015年 guoqw. All rights reserved.
//

import UIKit

class JiandanTableViewControlle: PFQueryTableViewController {

    //定义单元格的文本标识符
    let cellIdentifier:String = "CatCell"

    override init(style: UITableViewStyle, className: String!) {
        super.init(style: style, className: className)

        self.pullToRefreshEnabled = true
        self.paginationEnabled = false
        self.objectsPerPage = 25

        self.parseClassName = className

        self.tableView.rowHeight = 350
        self.tableView.allowsSelection = false
    }

    required init(coder aDecoder: NSCoder!) {
        fatalError("NSCoding not supported")
    }

    //数据查询
    override func queryForTable() -> PFQuery {
        var query:PFQuery = PFQuery(className: self.parseClassName!)
        if(objects?.count == 0){
            query.cachePolicy = PFCachePolicy.CacheThenNetwork
        }
        query.orderByAscending("name")
        return query
    }

    //数据展示
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, object: PFObject?) -> PFTableViewCell? {

        //定义单元格的文本标识符
        //let cellIdentifier:String = "Cell"
        //tableView 出列
        var cell:JiandanTableViewCell? = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as?JiandanTableViewCell
        //当单元格为空时，创建默认分格的PFTableViewCell
        if(cell == nil){
            cell = NSBundle.mainBundle().loadNibNamed("JiandanTableViewCell", owner: self, options: nil)[0] as? JiandanTableViewCell
        }
        //
        if let pfObject = object {
            //设置名称
            cell?.jiandanNameLabel?.text = pfObject["name"] as? String
            //设置投票数
            var votes:Int? = pfObject["votes"] as? Int
            if votes == nil {
                votes = 0
            }
            cell?.jiandanVotesLabel?.text = "\(votes!) votes"
            //设置作者
            var credit:String? = pfObject["cc_by"] as? String
            if credit != nil {
                cell?.jiandanCreditLabel?.text = "\(credit!) / CC 2.0"
            }
            //异步下载图像并显示
            if var urlString:String? = pfObject["url"] as? String {
                //print(urlString!)
                if var url:NSURL? = NSURL(string: urlString!) {
                    var error:NSError?
                    var rerquest:NSURLRequest = NSURLRequest(URL: url!, cachePolicy: NSURLRequestCachePolicy.ReturnCacheDataElseLoad, timeoutInterval: 5.0)

                    NSOperationQueue.mainQueue().cancelAllOperations();

                    NSURLConnection.sendAsynchronousRequest(rerquest, queue: NSOperationQueue.mainQueue(), completionHandler: {
                        (response:NSURLResponse!, imageData:NSData!, error:NSError!) -> Void in

                        cell?.jiandanImageView?.image = UIImage(data:imageData)
                    })

                    //                    NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {
                    //                        (response:NSURLResponse!, imageData:NSData!, error:NSError!) -> Void in
                    //
                    //                        cell?.catImageView?.image = UIImage(data: imageData)
                    //
                    //                    })
                }

            }
        }

        return cell;

    }

    override func viewDidLoad() {
        tableView.registerNib(UINib(nibName: "JiandanTableViewCell", bundle: nil), forCellReuseIdentifier:cellIdentifier)

        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    // Get the new view controller using segue.destinationViewController.
    // Pass the selected object to the new view controller.
    }
    */

}
